﻿"""
参考：Debian安装docker和docker-compose
https://article.juejin.cn/post/7216915438298284090

本脚本仅在某服务器刚装完 debian 11 后，初次启用时调用
mkdir tmp_for_start_docker_nginx && \
    apt update && \
    apt install git curl python3 -y && \
    git clone https://gitee.com/children1987/start_docker_nginx_debian.git tmp_for_start_docker_nginx/t && \
    python3 ./tmp_for_start_docker_nginx/t/start_nginx.py
"""

import os
import shutil
import subprocess


def cmd(cmd_str):
    print(cmd_str)
    if subprocess.call(cmd_str, shell=True):
        raise Exception("{} 执行失败".format(cmd_str))


def main():
    if os.geteuid() != 0:
        raise Exception("请以root权限运行")

    print("安装 docker 开始")
    cmd('''cd tmp_for_start_docker_nginx/t && \
        sudo sh test-docker.sh --mirror Aliyun --channel stable --version 28''')
    print("安装 docker 完成")

    cmd('cp ./tmp_for_start_docker_nginx/t/daemon.json /etc/docker/daemon.json')
    cmd('sudo systemctl daemon-reload')
    cmd('sudo systemctl restart docker')

    nginx_path = '/workspace/nginx'
    os.makedirs(nginx_path, exist_ok=True)

    log_path = '/workspace/nginx/log'
    os.makedirs(log_path, exist_ok=True)
    cmd(f'chmod -R 666 {log_path}')

    # 复制配置文件，如果目标文件已存在则覆盖
    nginx_conf_dest = os.path.join(nginx_path, 'nginx_base.conf')
    uwsgi_params_dest = os.path.join(nginx_path, 'uwsgi_params')
    error_pages_dest = os.path.join(nginx_path, 'error_pages')
    if os.path.exists(nginx_conf_dest):
        os.remove(nginx_conf_dest)
    if os.path.exists(uwsgi_params_dest):
        os.remove(uwsgi_params_dest)
    if os.path.exists(error_pages_dest):
        shutil.rmtree(error_pages_dest)
    shutil.move('./tmp_for_start_docker_nginx/t/nginx_base.conf', nginx_path)
    shutil.move('./tmp_for_start_docker_nginx/t/uwsgi_params', nginx_path)
    shutil.move('./tmp_for_start_docker_nginx/t/error_pages', nginx_path)

    # 如果 nginx 容器已存在，先停止并删除
    result = subprocess.run('docker ps -a --filter name=nginx --format "{{.Names}}"', shell=True, capture_output=True, text=True)
    if 'nginx' in result.stdout:
        print("检测到已存在的 nginx 容器，正在删除...")
        cmd('docker rm -f nginx')
    
    cmd('docker run --name nginx --restart always --network host -d -v /workspace/nginx/nginx_base.conf:/etc/nginx/nginx.conf -v /workspace/nginx/log:/var/log/nginx -v /workspace:/workspace nginx:1.28-alpine')
    cmd('docker exec nginx chown -R nginx:nginx /var/log/nginx/')
    cmd('docker exec nginx chmod -R 766 /var/log/nginx/')
    print("清理 tmp_for_start_docker_nginx 开始")
    shutil.rmtree('./tmp_for_start_docker_nginx', ignore_errors=True) 
    print("清理 tmp_for_start_docker_nginx 完成")


if __name__ == '__main__':
    main()
